package gold.digger;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.*;

/**
 * Created by fanzhenyu02 on 2020/6/27.
 * common problem solver template.
 */
public class LC133 {
    public long startExecuteTime = System.currentTimeMillis();

    public class Node {
        public int val;
        public List<Node> neighbors;

        public Node(int val) {
            this.val = val;
            this.neighbors = new ArrayList<>();
        }
    }


    class Solution {

        Map<Node, Node> map = new HashMap<>();

        public Node cloneGraph(Node node) {
            if (null == node) return null;

            Node cur;
            Deque<Node> queue = new LinkedList();
            queue.offerLast(node);
            map.put(node, new Node(node.val));

            while (!queue.isEmpty()) {
                cur = queue.pollFirst();
                for (Node neighbor : cur.neighbors) {
                    if (!map.containsKey(neighbor)) {
                        queue.offerLast(neighbor);
                        map.put(neighbor, new Node(neighbor.val));
                    }

                    map.get(cur).neighbors.add(map.get(neighbor));
                }
            }

            return map.get(node);
        }
    }

    public void run() {
        Solution solution = new Solution();
        Node n1 = new Node(1);
        Node n2 = new Node(2);
        Node n3 = new Node(3);
        Node n4 = new Node(4);

        n1.neighbors.add(n2);
        n1.neighbors.add(n4);

        n2.neighbors.add(n1);
        n2.neighbors.add(n3);

        n3.neighbors.add(n2);
        n3.neighbors.add(n4);

        n4.neighbors.add(n1);
        n4.neighbors.add(n3);

        System.out.println(solution.cloneGraph(n1));
    }

    public static void main(String[] args) throws Exception {
        LC133 an = new LC133();
        an.run();

        System.out.println("\ncurrent solution total execute time: " + (System.currentTimeMillis() - an.startExecuteTime) + " ms.");
    }
}
